package com.xlh.service.courseTest.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.poi.excel.cell.CellUtil;
import cn.hutool.poi.excel.style.StyleUtil;
import com.xlh.enums.course.ChapterTypeEnum;
import com.xlh.util.CellStyleUtils;
import com.xlh.util.StatisticExcelUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 章节统计excel模板下载
 */
@Service
public class ChapterStatisticsExcelExportImpl{

    // 理论课行二级列
    private final static String[] THEORY_SECOND_TITLE = {"序号", "学生姓名", "学生学号", "理论学习时长(小时)", "理论视频学习时长(小时)", "随堂练习分数",
            "优秀", "良好", "差劲", "正确", "错误"};

    // 理论及实验课二级列
    private final static String[] THEORY_AND_EXPER_SECOND_TITLE = {"序号", "学生姓名", "学生学号", "理论学习时长(小时)", "理论视频学习时长(小时)",
            "随堂练习分数","优秀", "良好", "差劲", "正确", "错误", "实验学习时长(小时)","实验视频学习时长(小时)", "实验分数", "实验是否通过"};

    // 实验课（单任务实验）
    private final static String[] EXPER_SECOND_TITLE = {"序号", "学生姓名", "学生学号", "实验学习时长(小时)", "实验视频学习时长(小时)", "实验分数", "实验是否通过"};

    /**
     * 获取excel对象
     * @param chapterTypeEnum
     * @param slogan
     * @return
     */
    public HSSFWorkbook getWorkBook( ChapterTypeEnum chapterTypeEnum , String slogan ){

        //通过工具类创建writer
        HSSFWorkbook workbook = new HSSFWorkbook();
        loadHeaderBySheet(chapterTypeEnum, slogan, workbook, "学生详情");
        return workbook;
    }

    /**
     * 传入workbook组装头信息
     * @param chapterTypeEnum
     * @param slogan
     * @param workbook
     */
    public HSSFSheet loadHeaderBySheet(ChapterTypeEnum chapterTypeEnum, String slogan, HSSFWorkbook workbook, String sheetName) {

        HSSFSheet studentDetail = workbook.createSheet(sheetName);
        // 头样式
        CellStyle titleStyle = getTitleStyle(workbook);
        // 副标题样式
        CellStyle subheadingStyle = getSubheading(workbook);
        // 第二行title
        String[] secondTitle = getSecondHeader(chapterTypeEnum);
        // 根据实验类型获取头文件行数
        Integer headerRows = getHeaderRows(chapterTypeEnum);

        for (int i = 0; i < headerRows; i++) {
            Row row = studentDetail.createRow(i);
            row.setHeight((short) 320);
            for (int j = 0; j < secondTitle.length; j++) {
                Cell cell = row.createCell(j);
                cell.setCellStyle(subheadingStyle);
                studentDetail.setColumnWidth(j, 256 * 12);
            }
        }
        // 第一行
        CellUtil.mergingCells(studentDetail, 0, 0, 0, (secondTitle.length - 1) , titleStyle);
        studentDetail.getRow(0).getCell(0).setCellValue(slogan);
        studentDetail.getRow(0).getCell(0).setCellStyle(titleStyle);
        studentDetail.getRow(0).setHeight((short)600);
        // 根据不同的实验类型调用不同的装载方法
        switch (chapterTypeEnum){
            case THEORY_MANY_EXPERIMENT:
            case THEORY:
                theoryLoad(studentDetail, subheadingStyle, secondTitle);
                break;
            case THEORY_EXPERIMENT:
                theoryExperimentLoad(studentDetail, subheadingStyle, secondTitle);
                break;
            case EXPERIMENT:
                experimentLoad(studentDetail, subheadingStyle, secondTitle);
                break;
        }
        return studentDetail;
    }

    /**
     * 根据实验类型获取表头行数
     * @param chapterTypeEnum
     * @return
     */
    private Integer getHeaderRows(ChapterTypeEnum chapterTypeEnum) {

        Integer headerRows = 0;
        switch (chapterTypeEnum){
            case THEORY_MANY_EXPERIMENT:
            case THEORY:
            case THEORY_EXPERIMENT:
                headerRows = 3;
                break;
            case EXPERIMENT:
                headerRows = 2;
                break;
        }
        return headerRows;
    }

    /**
     * 实验课第二行接口初始化
     * @param studentDetail
     * @param subheadingStyle
     * @param secondTitle
     */
    private void experimentLoad(Sheet studentDetail, CellStyle subheadingStyle, String[] secondTitle) {

        for (int columnIndex = 0; columnIndex < secondTitle.length ; columnIndex++) {
            studentDetail.getRow(1).getCell(columnIndex).setCellValue(secondTitle[columnIndex]);
            studentDetail.getRow(1).getCell(columnIndex).setCellStyle(subheadingStyle);
        }
    }

    /**
     * 理论及实验课装载第二行表头
     * @param studentDetail
     * @param subheadingStyle
     * @param secondTitle
     */
    private void theoryExperimentLoad(Sheet studentDetail, CellStyle subheadingStyle, String[] secondTitle) {

        for (int columnIndex = 0; columnIndex < secondTitle.length ; columnIndex++) {
            if(columnIndex < 6){
                mergeCellRow(studentDetail, 1, 2, columnIndex, secondTitle[columnIndex], subheadingStyle);
            }
            if(columnIndex == 6){
                CellUtil.mergingCells(studentDetail, 1, 1, columnIndex, 8, subheadingStyle);
                studentDetail.getRow(1).getCell(6).setCellValue(" 问答题表现 ");
                studentDetail.getRow(1).getCell(6).setCellStyle(subheadingStyle);
            }
            if(columnIndex == 9){
                CellUtil.mergingCells(studentDetail, 1, 1, columnIndex, 10, subheadingStyle);
                studentDetail.getRow(1).getCell(9).setCellValue(" 判断题表现 ");
                studentDetail.getRow(1).getCell(9).setCellStyle(subheadingStyle);
            }
            if(columnIndex >= 6){
                studentDetail.getRow(2).getCell(columnIndex).setCellValue(secondTitle[columnIndex]);
                studentDetail.getRow(2).getCell(columnIndex).setCellStyle(subheadingStyle);
            }

            if(columnIndex > 10){
                mergeCellRow(studentDetail, 1, 2, columnIndex, secondTitle[columnIndex], subheadingStyle);
            }

        }

    }

    /**
     * 理论课装载
     * @param studentDetail
     * @param subheadingStyle
     * @param secondTitle
     */
    private void theoryLoad(Sheet studentDetail, CellStyle subheadingStyle, String[] secondTitle) {
        for (int columnIndex = 0; columnIndex < secondTitle.length ; columnIndex++) {
            if(columnIndex < 6){
                mergeCellRow(studentDetail, 1, 2, columnIndex, secondTitle[columnIndex], subheadingStyle);
            }

            if(columnIndex >= 6){
                studentDetail.getRow(2).getCell(columnIndex).setCellValue(secondTitle[columnIndex]);
                studentDetail.getRow(2).getCell(columnIndex).setCellStyle(subheadingStyle);
            }

            if(columnIndex == 6){
                CellUtil.mergingCells(studentDetail, 1, 1, columnIndex, 8, subheadingStyle);
                studentDetail.getRow(1).getCell(6).setCellValue(" 问答题表现 ");
                studentDetail.getRow(1).getCell(6).setCellStyle(subheadingStyle);
            }
            if(columnIndex == 9){
                CellUtil.mergingCells(studentDetail, 1, 1, columnIndex, 10, subheadingStyle);
                studentDetail.getRow(1).getCell(9).setCellValue(" 判断题表现 ");
                studentDetail.getRow(1).getCell(9).setCellStyle(subheadingStyle);
            }

        }
    }

    /**
     * 根据实验类型获取二级Header
     * @param chapterTypeEnum
     * @return
     */
    private String[] getSecondHeader(ChapterTypeEnum chapterTypeEnum) {

        String[] secondHeader = null;
        switch (chapterTypeEnum){
            case THEORY_MANY_EXPERIMENT:
                secondHeader = THEORY_SECOND_TITLE;
                break;
            case THEORY_EXPERIMENT:
                secondHeader = THEORY_AND_EXPER_SECOND_TITLE;
                break;
            case THEORY:
                secondHeader = THEORY_SECOND_TITLE;
                break;
            case EXPERIMENT:
                secondHeader = EXPER_SECOND_TITLE;
                break;
        }
        return secondHeader;
    }

    /**
     * 行的头样式
     * @param workbook
     * @return
     */
    public static CellStyle getTitleStyle(HSSFWorkbook workbook) {

        HSSFPalette palette = workbook.getCustomPalette();
        // 设置主标题样式
        CellStyle titleStyle = workbook.createCellStyle();
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle.setAlignment(HorizontalAlignment.LEFT);
        titleStyle.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex());
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        palette.setColorAtIndex(HSSFColor.BLUE_GREY.index, (byte) 54, (byte) 96, (byte) 146);
        // 设置字体
        Font font = StyleUtil.createFont(workbook, IndexedColors.WHITE.index, (short) 12, "宋体");
        font.setBold(true);
        titleStyle.setFont(font);
        return titleStyle;
    }

    /**
     * 获取副标题样式
     * @return
     */
    public static CellStyle getSubheading(HSSFWorkbook workbook){

        HSSFPalette palette = workbook.getCustomPalette();
        // 设置副标题样式
        CellStyle titleStyle2 = workbook.createCellStyle();
        StatisticExcelUtil.setCellBorder(titleStyle2);
        titleStyle2.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex());
        titleStyle2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle2.setFont(StatisticExcelUtil.setFont(workbook, null, false, null));
        palette.setColorAtIndex(HSSFColor.SKY_BLUE.index, (byte) 197, (byte) 217, (byte) 241);

        return titleStyle2;
    }

    /**
     * 获取内容样式
     * @param workbook
     * @return
     */
    public static CellStyle getContentStyle(HSSFWorkbook workbook){
        // 设置内容的样式
        CellStyle contentStyle = workbook.createCellStyle();
        StatisticExcelUtil.setCellBorder(contentStyle);
        contentStyle.setFont(StatisticExcelUtil.setFont(workbook, null, false, null));
        return contentStyle;
    }

    /**
     * 对于行级别的cell进行合并
     * @param sheet
     * @param firstRow
     * @param lastRow
     * @param column
     * @param content
     * @param cellStyle
     * @return
     */
    private static Row mergeCellRow(Sheet sheet, int firstRow, int lastRow, int column, String content, CellStyle cellStyle) {
        Row row_2 = sheet.getRow(firstRow);
        CellUtil.mergingCells(sheet, firstRow, lastRow, column, column, cellStyle);
        row_2.getCell(column).setCellValue(content);
        row_2.getCell(column).setCellStyle(cellStyle);
        return row_2;
    }


    /**
     * 加载数据
     * @param sheet
     * @param data
     */
    public <T> void loadingData(HSSFSheet sheet,  List<T> data, List<String> filterName, CellStyle cellStyle) {

        int lastRowNum = sheet.getLastRowNum()+1;
        Field[] fields = data.get(0).getClass().getDeclaredFields();
        List<String> fieldsCollections = Arrays.stream(fields).map(field -> field.getName()).collect(Collectors.toList());
        fieldsCollections.removeAll(filterName);

        for (int i = lastRowNum; i < lastRowNum+data.size(); i++) {
            T obj = data.get(i - lastRowNum);
            HSSFRow row = sheet.createRow(i);
            for (int j = 0; j < fieldsCollections.size(); j++) {
                String fieldName = fieldsCollections.get(j);
                HSSFCell cell = row.createCell(j);
                cell.setCellStyle(cellStyle);

                if(fieldName.equals("index")){
                    cell.setCellValue(String.valueOf(i - lastRowNum + 1));
                }else{
                    Object fieldValue = BeanUtil.getFieldValue(obj, fieldName);
                    cell.setCellValue(String.valueOf(fieldValue));
                }
            }
        }
    }







}